<template>
	<view class="root">
		<!-- 使用 common-title 组件 -->
		<common-title :title="pageTitle" :showBack="false"></common-title>

		<view class="top-info">
			<view class="top-left">
				<uni-data-select v-model="selectValue" :localdata="selectTypeList" @change="onSelectTypeChange"
					placeholder="请选择类型" class="select-type"></uni-data-select>
				<uni-easyinput placeholder="请输标题搜索" class="input-title" v-model="titleContent" />

			</view>
			<view class="top-right" :style="{ backgroundColor: isDataSelected ? '#0F6AF8' : '#C7CACD' }"
				@click="sendHealthEdu()">
				<image src="/static/icon_send.png"></image>
				<view>下发</view>

			</view>
		</view>

		<scroll-view scroll-y="true" class="scroll-Y" v-if="!DataUtils.isEmpty(healthListRef)" refresher-enabled="true"
			:refresher-triggered="triggeredRef" :refresher-threshold="100" @refresherpulling="onPulling"
			@refresherrefresh="onRefresh" @refresherrestore="onRestore" @refresherabort="onAbort">
			<view class="content">
				<uni-grid :column="4" :showBorder="false" borderColor="#00000000">
					<view v-for="(item, position) in healthListRef" :key="position" class="item-content"
						@click="showItemDetail(item)">

						<view class="item-logo-container">
							<image class="item-logo" :src="item.imageUrl"></image>
							<image
								:src="item.checked ? '/static/icon_check_selected.png' : '/static/icon_check_unselect.png'"
								class="v-select" @click.stop="selectItem(item)" />

						</view>
						<view class="item-title">{{item.title}}</view>
						<view class="item-date">{{item.releaseTime}}</view>
					</view>
				</uni-grid>
			</view>
		</scroll-view>

		<scroll-view scroll-y="true" class="scroll-Y" refresher-enabled="true" :refresher-triggered="triggeredRef"
			:refresher-threshold="100" @refresherpulling="onPulling" @refresherrefresh="onRefresh"
			@refresherrestore="onRestore" @refresherabort="onAbort" v-else>
			<NoData></NoData>
		</scroll-view>



		<!-- 健康宣教下方 提示框 -->
		<uni-popup ref="tiosPopRef" background-color="#fff">
			<view class="tip-pop-container">
				<view class="view-title"><text>下方任务</text></view>
				<uni-forms-item label="健康宣教标题" required class="uni-view-helth-title">
					<view class="view-helth-title">
						{{titleListStr}}
					</view>
				</uni-forms-item>

				<uni-forms-item label="接受病床" required class="uni-view-select-bed">
					<view class="view-view-select-bed">
						<view class="view-bed-item" v-for="(item, index) in checkBedList" :key="index">{{item.orgName}}
						</view>

					</view>
				</uni-forms-item>



				<uni-forms-item label="阅读要求" required class="uni-forms-item-read-type">
					<uni-data-checkbox v-model="readType" :localdata="readTypeList" />
				</uni-forms-item>

				<view class="view-btn">
					<view class="cancel" @click="cancel">取消</view>
					<view class="confirm" @click="confirm">确定</view>
				</view>

			</view>



		</uni-popup>

		<!-- 右滑菜单，病床 -->
		<SelectBed ref="selectBedRef" v-model:showRight="showRight" v-model:checkBedList="checkBedList"
			:checkedSelect="true" v-model:orgId="initInfo.orgId"></SelectBed>

	</view>
</template>

<script setup>
	import * as httpConfig from "../../common/http-config.js";
	import * as DataUtils from "../../utils/DataUtils";
	import CommonTitle from '@/components/common-title.vue';
	import SelectBed from '@/components/select-bed.vue';
	import NoData from '@/components/no-data.vue';
	import {
		ref,
		onMounted,
		onUnmounted,
		getCurrentInstance,
		computed,
		defineComponent,
		watch,
		reactive
	} from 'vue'

	import {
		onLoad,
		onShow,
		onHide
	} from '@dcloudio/uni-app'
	const pageTitle = ref("健康宣教")
	const titleContent = ref("")
	const showRight = ref(false)
	const checkBedList = ref([])
	// 获取当前组件实例
	const instance = getCurrentInstance()
	// 定义响应式变量
	const initInfo = ref({})

	const triggeredRef = ref(true)

	const onPulling = (e) => {
		console.log("onPulling")

	}
	const onRefresh = () => {
		console.log("onRefresh")
		triggeredRef.value = true; // 开始刷新
		healthList()
	}

	const onRestore = () => {
		console.log("onRestore")
	}

	const onAbort = () => {
		console.log("onAbort")
	}


	// 使用 onMounted 钩子自动播放视频
	onMounted(() => {
		console.log("组件已经挂载了.......")



	});

	onShow(() => {
		console.log("onShow...")
		if (instance?.proxy?.$globalData?.initInfo) {
			let jsonStr = instance.proxy.$globalData.initInfo;
			console.log("onShow jsonStr = " + jsonStr)
			initInfo.value = JSON.parse(jsonStr)
			console.log("onShow initInfo = " + initInfo.value)
			healthList()
		}

	})

	onLoad((option) => {

		const areaId = option.areaId;
		const orgId = option.orgId;
		const deviceType = option.deviceType;

		console.log("areaId = " + areaId);
		console.log("deviceType = " + deviceType);
		console.log("orgId = " + orgId);
		if (!DataUtils.isEmpty(areaId) && !DataUtils.isEmpty(deviceType) && !DataUtils.isEmpty(orgId)) {
			// 通过 options 获取参数
			initInfo.value["areaId"] = areaId
			initInfo.value["deviceType"] = deviceType
			initInfo.value["orgId"] = orgId
			healthList()
		}

	})

	onHide(() => {
		console.log("onHide...")

	})


	watch(
		() => checkBedList.value, // 监听 newsContentType
		(newValue, oldValue) => {
			if (!DataUtils.isEmpty(newValue)) {
				showTipDialog()
			}
		}
	);



	// 选择病床
	const selectBedList = () => {
		console.log("selectBedList")
		showRight.value = true

	}


	watch(
		() => titleContent.value, // 监听 newsContentType
		(newValue, oldValue) => {
			// 在这里处理 newsContentType 变化后的逻辑
			console.log("titleContent " + oldValue + "," + newValue)
			healthList()
		}
	);


	const isDataSelected = computed(() => {
		const selectCount = healthListRef.value.filter(item => item.checked).length;
		return selectCount > 0;
	});
	// 选中
	const selectItem = (item) => {
		console.log("selectItem" + item)
		item.checked = !item.checked
	}
	// 展示健康宣教详情
	const showItemDetail = (item) => {
		console.log("showItemDetail" + item.introduceId)
		if (item["contentStyle"] == "video") {
			uni.navigateTo({
				url: 'video-page?introduceId=' + item.introduceId
			});
		} else {
			uni.navigateTo({
				url: 'text-pic-page?introduceId=' + item.introduceId
			});
		}
	}

	const selectValue = ref(null)
	const selectTypeList = ref([{
			value: "image_text",
			text: "图文"
		},
		{
			value: "video",
			text: "视频"
		}
	])
	const onSelectTypeChange = () => {
		console.log("onSelectTypeChange " + selectValue.value)
		healthList()
	}
	const sendHealthEdu = () => {
		if (isDataSelected.value) {
			selectBedList()
			// showTipDialog()

		} else {
			console.log("sendHealthEdu 未选中")


		}

	}
	const readTypeList = ref([{
		text: '不强制要求',
		value: "no_compulsory_read"
	}, {
		text: '强制要求',
		value: "compulsory_read"
	}])
	const readType = ref("no_compulsory_read")


	const tiosPopRef = ref(null)
	// 下发健康宣教
	const showTipDialog = () => {
		console.log("showTipDialog")
		tiosPopRef.value.open(); // 调用 uni-popup 的 open 方法
	}

	const healthListRef = ref([])
	// 获取健康宣教
	const healthList = async () => {
		uni.request({
			url: httpConfig.baseURL + httpConfig.healthList, // 请求的 URL
			method: 'POST', // 请求方法为 POST
			data: {
				"currentPage": 1,
				"pageSize": 50,
				"title": titleContent.value,
				"contentStyle": selectValue.value,
				"deviceType": initInfo.value["deviceType"],
				"areaId": initInfo.value["areaId"]
			},
			success: (res) => {
				console.log('healthList success', res.data.data);
				triggeredRef.value = false
				if (res.data.code == httpConfig.successCode) {
					healthListRef.value = res.data.data["items"]
				}
				// 在这里处理请求成功的情况
			},
			fail: (err) => {
				triggeredRef.value = false
				console.error('healthList fail employeeInfo', err);
				// 在这里处理请求失败的情况
			}
		});
	};

	// 选择的健康宣教的标题
	const titleListStr = computed(() => {
		return healthListRef.value.map(item => item.title).join(',');
	});

	const cancel = () => {
		console.log("cancel")
		tiosPopRef.value.close(); // 调用 uni-popup 的 open 方法
	}
	const confirm = () => {
		console.log("confirm")
		tiosPopRef.value.close(); // 调用 uni-popup 的 open 方法
		healthPush();
	}
	const healthPush = () => {

		// 选择的健康宣教的数据
		const healthEducations = healthListRef.value
			.filter(item => item.checked) // 过滤出 checked 为 true 的项
			.map(item => ({
				introduceId: item.introduceId, // 提取 introduceId
				imageUrl: item.imageUrl,

				title: item.title // 提取 title
			}));
		const bedIds = checkBedList.value.map(item => item.orgId);

		let data = {
			"bedIds": bedIds,
			"orgId": initInfo.value.orgId,
			"healthEducations": healthEducations,
			"compulsoryRead": readType.value // compulsory_read 强制阅读，no_compulsory_read 不强制阅读
		}
		console.log("healthPush " + JSON.stringify(data))

		uni.request({
			url: httpConfig.baseURL + httpConfig.healthPush, // 请求的 URL
			method: 'POST', // 请求方法为 POST
			data: data,
			success: (res) => {
				console.log('healthPush success', res.data.data);
				if (res.data.code == httpConfig.successCode) {
					uni.showToast({
						title: '下发成功',
						icon: "success",
						duration: 2000,
					});
					// 重置选择
					healthListRef.value.forEach((item) => {
						item["checked"] = false
					})
				} else {
					uni.showToast({
						title: res.data.message,
						icon: "error",
						duration: 2000
					});
				}
				// 在这里处理请求成功的情况
			},
			fail: (err) => {
				console.error('orgBedList fail ', err);
				uni.showToast({
					title: err,
					icon: "error",
					duration: 2000
				});
				// 在这里处理请求失败的情况
			}
		});


	}
</script>

<style>

</style>
<style lang="less" scoped>
	@vw: 8.015vw;
	@vh: 5.4vh;

	.root {
		height: 100vh;
		/* 页面高度为 100% */
		overflow: hidden;
		/* 禁止页面滚动 */
		display: flex;
		flex-direction: column;

		.common-title {
			font-size: 13/@vh;
			color: #2C2E30;

			margin-left: 16/@vw;
			margin-top: 18/@vh;

		}

		.top-info {

			display: flex;
			flex-direction: row;
			justify-content: space-between;
			font-size: 13/@vh;
			color: #C7CACD;

			.top-left {

				display: flex;
				align-items: center;
				flex-direction: row;
				margin-left: 16/@vw;
				color: #222222;
				font-size: 13/@vh;


				.select-type {
					width: 168/@vw;
					margin-top: 0/@vh;
					margin-left: 0/@vh;



				}

				.input-title {
					margin-left: 20/@vw;
					width: 168/@vw;

				}


			}

			.top-right {
				width: 63/@vw;
				height: 32/@vh;
				border-radius: 3/@vh;
				background-color: #0F6AF8;
				margin-right: 16/@vw;
				color: white;
				display: flex;
				justify-content: center;
				font-size: 13/@vh;
				align-items: center;

				image {
					margin-right: 2/@vw;
					width: 14/@vw;
					height: 14/@vh;
				}
			}
		}

		scroll-view {
			height: 100%;
			overflow: auto;
			margin-top: 20/@vh;

			.item-content {
				width: 176/@vw;
				margin-left: 16/@vh;
				margin-bottom: 32/@vh;

				.item-logo-container {
					width: 100%;
					height: 110/@vh;
					position: relative;

					.item-logo {
						width: 100%;
						height: 100%;
						border-radius: 6/@vh;
						object-fit: cover;
						/* 用于 <img> 标签 */
					}


					.v-select {
						top: 5/@vw;
						right: 5/@vw;
						width: 22/@vw;
						height: 22/@vh;
						position: absolute;
					}
				}



				.item-title {
					width: 150/@vw;
					white-space: nowrap;
					/* 强制文本一行显示 */
					overflow: hidden;
					text-overflow: ellipsis;
					font-size: 13/@vh;
					margin-top: 7/@vh;
					color: #000000;
					font-weight: bold;
				}

				.item-date {
					width: 176/@vw;
					white-space: nowrap;
					/* 强制文本一行显示 */
					overflow: hidden;
					text-overflow: ellipsis;
					font-size: 10/@vh;
					margin-top: 1/@vh;
					color: #7F848C;
				}
			}




		}


	}

	::v-deep.uni-forms-item__label {
		color: #2C2E30;
		font-size: 13/@vh;
	}

	::v-deep.uni-data-checklist .checklist-group .checklist-box .checklist-content .checklist-text {
		font-size: 13/@vh;
		color: #2C2E30;
	}



	// 输入框
	::v-deep.uni-easyinput__content-input {

		height: 34/@vh;
		font-size: 13/@vh;
		color: #2C2E30;
	}

	::v-deep.uni-easyinput__placeholder-class {
		font-size: 13/@vh;

	}

	::v-deep.uni-select {
		height: 36/@vh;
		font-size: 13/@vh;
		color: #2C2E30;
	}

	::v-deep.uni-select__selector-item {
		font-size: 13/@vh !important;
	}

	::v-deep.uni-icons {
		font-size: 20/@vh !important;
	}

	::v-deep.uni-select__input-placeholder {
		font-size: 13/@vh !important;
	}

	::v-deep.uni-forms-item__label {
		width: 105/@vw !important;
	}

	::v-deep.uni-forms-item {
		margin: 0;
		display: flex;
		flex-direction: row;
		align-items: center;

	}

	::v-deep.uni-easyinput__content-textarea {
		height: 90/@vh ;
		font-size: 13/@vh;
		color: #2C2E30;
		min-height: 0px;

	}

	::v-deep.uni-drawer__content {
		width: 340/@vw !important;
	}

	::v-deep.uni-select__input-placeholder {
		font-size: 13/@vh !important;
	}

	::v-deep.uni-date__x-input {
		font-size: 13/@vh !important;
		height: 34/@vh;
		line-height: 34/@vh;
	}

	.tip-pop-container {
		width: 500/@vw;
		height: 320/@vh;
		flex-direction: column;
		display: flex;
		align-items: start;

		.view-title {
			margin-top: 21/@vh;
			font-size: 14/@vh;
			font-weight: bold;
			width: 100%;
			display: flex;
			flex-direction: row;
			justify-content: center;
		}

		.uni-view-helth-title {
			margin-top: 24/@vh;
			margin-left: 34/@vw;


			.view-helth-title {

				line-height: 34/@vh;
				align-items: center;
				background-color: white;
				border: 1px solid #dcdfe6;
				background-color: ;
				border-radius: 4px;
				padding-left: 10/@vw;
				color: #2C2E30;
				width: 300/@vw;
				height: 34/@vh;
				white-space: nowrap;
				/* 强制文本一行显示 */
				overflow: hidden;
				text-overflow: ellipsis;
				font-size: 13/@vh;



			}
		}

		.uni-view-select-bed {
			margin-top: 24/@vh;
			margin-left: 34/@vw;

			.view-view-select-bed {
				display: flex;
				flex-wrap: wrap;
				/* 允许子元素换行 */
				justify-content: flex-start;
				background-color: white;
				border: 1px solid #dcdfe6;
				background-color: ;
				border-radius: 4px;
				color: #2C2E30;
				width: 300/@vw;
				height: 68/@vh;
				white-space: nowrap;
				/* 强制文本一行显示 */
				max-lines: 2;
				overflow: auto;

				font-size: 13/@vh;


				.view-bed-item {
					margin-left: 5/@vw;
					margin-top: 5/@vh;
					background-color: #EFF0F4;
					color: #586F93;
					font-size: 13/@vh;
					padding-left: 8/@vw;
					padding-right: 8/@vw;
					border-radius: 2/@vh;
					display: flex;
					align-items: center;
					height: 29/@vh;
				}

			}

		}


		.uni-forms-item-read-type {
			margin-left: 34/@vw;
			margin-top: 10/@vh;
		}

		.view-btn {
			display: flex;
			flex-direction: row;
			justify-content: center;
			width: 100%;
			align-items: center;
			margin-top: 28/@vh;
			font-size: 13/@vh;

			.cancel {
				margin-right: 33/@vw;
				display: flex;
				justify-content: center;
				align-items: center;
				width: 50/@vw;
				height: 28/@vh;
				border-radius: 3/@vh;
				border: 0.5/@vh solid #0F6AF8;
				color: #2C2E30;
			}

			.confirm {
				margin-right: 24/@vw;
				display: flex;
				justify-content: center;
				align-items: center;
				width: 50/@vw;
				height: 28/@vh;
				border-radius: 3/@vh;
				background-color: #0F6AF8;
				color: white;
			}
		}

	}
</style>